package com.example.wx_zl_gzh_demo.common.token;

import com.example.wx_zl_gzh_demo.common.util.HttpUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * $
 $ * @return $
 * @author $
 * @description 获取access_token
 * @date $ $
 */
public class TokenUtil {
    /*https请求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential
     &appid=APPID&secret=APPSECRET*/
    // TODO 提成可配置存库
    private static final String APP_ID="wx6f18004c569546a5";
    private static final String APP_SECRET="1a963c357e804ee388f311fb3ceebda0";
    private static final Logger log = LoggerFactory.getLogger(TokenUtil.class);
    private static AccessToken accessToken=new AccessToken();

    private static void getToken(){
        String  api= "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
        String url = String.format(api, APP_ID, APP_SECRET);
        String result = HttpUtil.doGet(url);
        log.info(result);
        JSONObject jsonObject = JSONObject.fromObject(result);
        String token = jsonObject.getString("access_token");
        long expiresIn = jsonObject.getLong("expires_in");
        accessToken.setToken(token);
        accessToken.setExpireTime(expiresIn);

    }
    /**
     * @param :
     * @return String
     * @author Administrator
     * @description 获取AccessToken
     * @date 2024/6/22 下午8:52
     */
    public static String getAccessToken() {
        synchronized (TokenUtil.class) {
            if (accessToken == null || accessToken.isExpired()) {
                getToken();
            }
            return accessToken.getToken();
        }
    }
    public static void main(String[] args) {
        /*{"access_token":"81_7CL0bhuGZ-sQQ6pX-o_KszFrOmmnFJ8sura27Xm88nBqxn6rMXSXTB8D1ipO8_ICWU5BxAJd_7MKkdFs9okMT1Ynnw-enmLo7N7bLp-xFyZzYcX5KpXF0K992sMXNYhAJAOEP","expires_in":7200}*/
        log.info(getAccessToken());
        log.info(getAccessToken());
    }
}
